package net.wanho.shiro.dao;

import lombok.extern.slf4j.Slf4j;
import net.wanho.shiro.constant.ShiroConstants;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class ShiroSessionDao extends EnterpriseCacheSessionDAO {

    @Autowired
    private RedisTemplate<Serializable,Session> redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = ShiroConstants.SHIRO_SESSION_PREFIX+ UUID.randomUUID().toString();
        this.assignSessionId(session, sessionId);
        log.info("create shiro session,session id is:{}", sessionId);
        redisTemplate.opsForValue().set(sessionId,session,ShiroConstants.SESSION_TIMEOUT, TimeUnit.SECONDS);
        return  sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.info("read shiro session,session id is:{}", sessionId.toString());
        // 先更新
        redisTemplate.expire(sessionId,ShiroConstants.SESSION_TIMEOUT, TimeUnit.SECONDS);
        // 再读取
        Session session = redisTemplate.opsForValue().get(sessionId);
        return session;
    }

    @Override
    protected void doUpdate(Session session) {
        log.info("update shiro session,session id is:{}", session.getId().toString());
        redisTemplate.opsForValue().set(session.getId(),session,ShiroConstants.SESSION_TIMEOUT, TimeUnit.SECONDS);
    }

    @Override
    protected void doDelete(Session session) {
        log.info("delete shiro session,session id is:{}", session.getId().toString());
        redisTemplate.delete(session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Serializable> sessionIds = redisTemplate.keys(ShiroConstants.SHIRO_SESSION_PREFIX_KYES);
        if(StringUtils.isEmpty(sessionIds))
            return Collections.emptySet();
        List<Session> sessions = redisTemplate.opsForValue().multiGet(sessionIds);
        //可以得到一个集合的镜像，它的返回结果不可直接被改变,否则会提示//java.lang.UnsupportedOperationException
        return Collections.unmodifiableCollection(sessions);
    }


}
